/*$(document).ready(function () {
    App.init();
    TableManageFixedHeader.init();

    $('.datepicker-default').datepicker({
        language: 'zh-CN',//显示中文
        format: 'yyyy-mm-dd',//显示格式
        minView: "month",//设置只显示到月份
        initialDate: new Date(),//初始化当前日期
        autoclose: true,//选中自动关闭
        todayBtn: 'linked'//显示今日按钮
    });

});*/
$(document).ready(function() {

    App.init();
    TableManageFixedHeader.init();
    wrapTable1();
    wrapTable2();
    var m = $("#m1").val();
    if(m!=null){
        if (m=='0'){
            showRead();
        }else if(m == '1'){
            showAlread();
        }
    }
    var types = $("#types").val();
    if (types!=null){
        var n =null;
        var id = '';
        if(types == '2'){
            n = "税点设置";
            id = "tab4";
        }else if(types == '3'){
            n = "自留点位设置";
            id = "tab5";
        }else if(types == '5'){
            n = "产品详情";
            id = "tab7";
        } else if(types == '6'){
            n = "审核";
            id = "tab6";
        }else if(types == '4'){
            $("#myTab li:eq(0)").removeClass("active");
            $("#myTab li:eq(1)").removeClass("active");
            $("#myTab li:eq(3)").removeClass("active");
            $("#myTab li:eq(3)").remove();
            //$('#myTab a:first').tab('hide');
            $("#tab1").removeClass(" active in");
            $("#tab2").removeClass(" active in");
            $("#tab4").removeClass(" active in");
            $("#tab5").removeClass(" active in");
            $("#tab6").removeClass(" active in");
            $("#tab7").removeClass(" active in");
            $("#myTab li:eq(2)").addClass("active");
            $("#tab3").addClass(" active in")
        }
        if(n!=null){
            var ul = document.getElementById("myTab")//定位ul

            var li= document.createElement("li"); //创建li
            var href_a = document.createElement("a"); //创建li中的链接a
            href_a.href="javascript:void(0)"; //连接地址或执行函数
            href_a.innerHTML =n; //链接显示文本（相当于标签标题）
            //li.innerHTML=""; //标签页的标题
            li.id="d1"; //标签页ID

            li.appendChild(href_a);//将a添加到li
            ul.appendChild(li); //将li添加到ul

            //$('#myTab a:first').tab('hide');
            $("#myTab li:eq(3)").addClass("active");
            $("#myTab li:eq(0)").removeClass("active");
            $("#myTab li:eq(1)").removeClass("active");
            $("#tab1").removeClass(" active in");
            $("#tab2").removeClass(" active in");
            $("#"+id).addClass(" active in");
            $("#types").val(null);
        }

    }

    var count = $("#count").val();
    var storage=window.localStorage;
    if(count!=0){
        var i = storage.setItem("i",parseInt(count)+1);
    }else{
        var i = storage.setItem("i",2);
    }

    //日期控件
    $("#datetimepicker").datepicker({
        autoclose: true, //自动关闭
        beforeShowDay: $.noop,    //在显示日期之前调用的函数
        calendarWeeks: false,     //是否显示今年是第几周
        clearBtn: false,          //显示清除按钮
        daysOfWeekDisabled: [],   //星期几不可选
        endDate: Infinity,        //日历结束日期
        forceParse: true,         //是否强制转换不符合格式的字符串
        format: 'yyyy-mm-dd',     //日期格式
        keyboardNavigation: true, //是否显示箭头导航
        language: "zh-CN",           //语言
        minViewMode: 0,
        orientation: "auto",      //方向
        rtl: false,
        startDate: -Infinity,     //日历开始日期
        startView: 0,             //开始显示
        todayBtn: false,          //今天按钮
        todayHighlight: true,    //今天高亮
        weekStart: 0
    });


    //业务员赋值
    $("#email").click(function () {
        var value = $("#email :selected").val();
        if(value!="请选择"){
            $('#userName').val($('#email :selected').text());
        }
    });

    //保险公司赋值
    $("#select").click(function () {
        var value = $('#select :selected').val();
        if(value!="请选择"){
            $('#company').val($('#select :selected').text());
        }
    })
});


//分页展示
var table1;
var table2;
function wrapTable1() {
    table1 = $("#modeltable").DataTable({
        "bAutoWidth": false,
        "order": [[0, 'desc']],
        "pagingType": "simple_numbers",//设置分页控件的模式
        searching: false,//屏蔽datatales的查询框
        aLengthMenu: [15],//设置一页展示10条记录
        "bLengthChange": false,//屏蔽tables的一页展示多少条记录的下拉列表
        "oLanguage": {  //对表格国际化
            "sLengthMenu": "每页显示 _MENU_条",
            "sZeroRecords": "没有找到符合条件的数据",
            "sInfo": "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
            "sInfoEmpty": "没有记录",
            "sInfoFiltered": "(从 _MAX_ 条记录中过滤)",
            "sSearch": "搜索：",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            }
        },
        "processing": true, //打开数据加载时的等待效果
        "serverSide": true,//打开后台分页
        "ajax": {
            "url": "/product/list",
            "dataSrc": "aaData",
            "data": function (params) {
                var com = $('#companyId :selected').val();
                if (com == '-1'){
                    params.companyId = null;
                }else{
                    params.companyId = com;
                }
                var ty = $('#type :selected').val();
                if(ty=='2'){
                    params.type = null;
                }else{
                    params.type = ty;
                }
            }
        },
        "columns": [
            {
                "render": function (data, type, row, meta) {
                    var id = row.productId;
                    var tids = row.tid;
                    return "<a href='javascript:void(0);' onclick='toDetails("+tids+")'>"+id+"</a>";
                }
            },
            {"data": "company",
                "bSortable": false
            },
            {
                "render": function (data, type, row, meta) {
                    var status = "";
                    if(row.type=='0'){
                        status = "交强险";
                    }else if(row.type=='1'){
                        status = "商业险";
                    }
                    return status;
                }
            },
            {
                "data": "contractTime",
                "bSortable": false
            },
            {
                "render": function (data, type, row, meta) {
                    var status = "";
                    if(row.separateStatus=='1'){
                        status = "是";
                    }else if(row.separateStatus=='2'){
                        status = "否";
                    }
                    return status;
                }
            },
            {
                "render": function (data, type, row, meta) {
                    var status = "";
                    if(row.modalityStatus=='1'){
                        status = "现金";
                    }else if(row.modalityStatus=='2'){
                        status = "三方开票";
                    }
                    return status;
                }
            },
            {
                "render": function (data, type, row, meta) {
                    var status = "";
                    if(row.checkStatus=='0'){
                        status = "设置定价中";
                    }else if(row.checkStatus=='1'){
                        status = "审核中";
                    }else if(row.checkStatus=='2'){
                        status = "审核驳回";
                    }
                    return status;
                }
            }
        ],

        "columnDefs": [{
            "targets": 7,//是操作按钮目标列
            "data": null,
            "render": function (data, type, row) {
                var ids = row.tid;
                if(row.checkNode!=null){
                    if(row.checkNode==0){
                        if(row.checkStatus=='2'){
                        /*<shiro:hasPermission name="产品管理-产品列表">

                                </shiro:hasPermission>*/
                            return "<shiro:hasPermission name='产品列表-税点设置'>" +
                                "<a href='javascript:void(0);' onclick='updatePoint("+ids+",0)'>税点设置</a>" +
                                "</shiro:hasPermission>" +
                                "&nbsp;&nbsp;&nbsp;<a href='javascript:void(0);' onclick='openModel("+ids+",5)'>删除</a>";
                            /*deleteById("+ids+")*/
                        }else{
                            return "<shiro:hasPermission name='产品列表-税点设置'>" +
                                "<a href='javascript:void(0);' onclick='updatePoint("+ids+",0)'>税点设置</a>" +
                                "</shiro:hasPermission>";
                        }
                    }else if(row.checkNode==1){
                        return "<a href='javascript:void(0);' onclick='updateEaringPoint("+ids+",0)'>自留点位设置</a>";
                    }else if(row.checkNode==3){
                        return "<a href='javascript:void(0);' onclick='toCheckPage("+ids+",0)'>审核</a>";
                    }else if(row.checkNode==4){
                        return "<a href='javascript:void(0);' onclick='toCheckPage("+ids+",1)'>审核</a>";
                    }
                }


            }
        }]
    });

}

function wrapTable2() {
    table2 = $("#modeltable1").DataTable({
        "bAutoWidth": false,
        "order": [[0, 'desc']],
        "pagingType": "simple_numbers",//设置分页控件的模式
        searching: false,//屏蔽datatales的查询框
        aLengthMenu: [15],//设置一页展示10条记录
        "bLengthChange": false,//屏蔽tables的一页展示多少条记录的下拉列表
        "oLanguage": {  //对表格国际化
            "sLengthMenu": "每页显示 _MENU_条",
            "sZeroRecords": "没有找到符合条件的数据",
            "sInfo": "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
            "sInfoEmpty": "没有记录",
            "sInfoFiltered": "(从 _MAX_ 条记录中过滤)",
            "sSearch": "搜索：",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            }
        },
        "processing": true, //打开数据加载时的等待效果
        "serverSide": true,//打开后台分页
        "ajax": {
            "url": "/product/list",
            "dataSrc": "aaData",
            "data": function (params) {
                var com = $('#companyId1 :selected').val();
                if (com == '-1'){
                    params.companyId = null;
                }else{
                    params.companyId = com;
                }
                var ty = $('#type1 :selected').val();
                if(ty=='2'){
                    params.type = null;
                }else{
                    params.type = ty;
                }
                var value = $('#useStatus :selected').val();
                if(value=='2'){
                    params.useStatus = null;
                }else{
                    params.useStatus = value;
                }
                params.t = 1;
            }
        },
        "columns": [
            {
                "render": function (data, type, row, meta) {
                    var id = row.productId;
                    var tids = row.tid;
                    return "<a href='javascript:void(0);' onclick='toDetails("+tids+")'>"+id+"</a>";
                }
            },
            {"data": "company",
                "bSortable": false
            },
            {
                "render": function (data, type, row, meta) {
                    var status = "";
                    if(row.type=='0'){
                        status = "交强险";
                    }else if(row.type=='1'){
                        status = "商业险";
                    }
                    return status;
                }
            },
            {
                "data": "contractTime",
                "bSortable": false
            },
            {
                "render": function (data, type, row, meta) {
                    var status = "";
                    if(row.separateStatus=='1'){
                        status = "是";
                    }else if(row.separateStatus=='2'){
                        status = "否";
                    }
                    return status;
                }
            },
            {
                "render": function (data, type, row, meta) {
                    var status = "";
                    if(row.modalityStatus=='1'){
                        status = "现金";
                    }else if(row.modalityStatus=='2'){
                        status = "三方开票";
                    }
                    return status;
                }
            },
            {
                "render": function (data, type, row, meta) {
                    var status = "";
                    if(row.useStatus=='0'){
                        status = "已启用";
                    }else if(row.useStatus=='1'){
                        status = "已禁用";
                    }
                    return status;
                }
            }
        ],

        "columnDefs": [{
            "targets": 7 ,//是操作按钮目标列
            "data": null,
            "render": function (data, type, row) {
                var ids = row.tid;
                if(row.useStatus=='0'){
                    return "<a href='javascript:void(0);' onclick='updatePoint("+ids+",1)'>税点设置</a>&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "<a href='javascript:void(0);' onclick='updateEaringPoint("+ids+",1)'>自留点位设置</a>&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "<a href='javascript:void(0);' onclick='openModel("+ids+",1)'>禁用</a>";
                    /*chageNotUse("+ids+",1)*/
                }else {
                    return "<a href='javascript:void(0);' onclick='openModel("+ids+",2)'>启用</a>";
                    /*chageToUse("+ids+",0)*/
                }

            }
        }]
    });

}

//删除
function deleteById(tid) {
    /*if(confirm("确认删除此产品？")){
    }*/
        $.post(
            "/product/deleteById",
            {tid:tid},
            function (msg) {
                if (msg){
                    showRead();
                    //location = location;
                }
            },"json"
        );
}

//设置业务员
function changeSalesman() {
    $('#email option').remove();
    var tid = $("#select :selected").val();
   $.post(
       "/product/getSlaesmenByCompanyId",
       {tid:tid},
       function (data) {
           if(data!=null){
               for (var i in data){
                    $("#email").append("<option value=''>请选择</option><option value='"+data[i].userId+"'>"+data[i].userName+"</option>");
               }
           }
       },"json"
   );
}

//税点设置
function updatePoint(tid,type) {
    window.location.href = "/product/updatePoint?tid="+tid+"&m="+type;
}

//自留点位设置
function updateEaringPoint(tid,type) {
    window.location.href = "/product/earingPoint?tid="+tid+"&m="+type;
}

//去审核页面
function toCheckPage(tid,type) {
    window.location.href = "/product/check?tid="+tid+"&t="+type;
}

//详情页
function toDetails(tid) {
    window.location.href = "/product/getDetails?tid="+tid;
}

//查询
function search() {
    table1.ajax.reload();
}
function search1() {
    table2.ajax.reload();
}

//展示待定价
function showRead() {
    table1.ajax.reload();

    $("#myTab li:eq(0)").addClass("active");
    $("#tab1").addClass("active in");
    $("#myTab li:eq(1)").removeClass("active");
    $("#myTab li:eq(2)").removeClass("active");
    $("#myTab li:eq(3)").removeClass("active");
    $("#myTab li:eq(3)").remove();
    $("#tab2").removeClass(" active in");
    $("#tab3").removeClass(" active in");
    $("#tab4").removeClass(" active in");
    $("#tab5").removeClass(" active in");
    $("#tab6").removeClass(" active in");
    $("#tab7").removeClass(" active in");
    $("#tab1").show();
}

// 展示已定价
function showAlread() {
    table2.ajax.reload();

    $("#tab1").hide();
    $("#myTab li:eq(0)").removeClass("active");
    $("#myTab li:eq(2)").removeClass("active");
    $("#myTab li:eq(3)").removeClass("active");
    $("#myTab li:eq(3)").remove();
    $("#tab1").removeClass(" active in");
    $("#tab3").removeClass(" active in");
    $("#tab4").removeClass(" active in");
    $("#tab5").removeClass(" active in");
    $("#tab6").removeClass(" active in");
    $("#tab7").removeClass(" active in");
    $("#myTab li:eq(1)").addClass("active");
    $("#tab2").addClass(" active in")

}

//打开模态框
function openModel(ids,type) {

    $("#tid").val(ids);
    $("#typee").val(type);
    if (type==1){
        $("#me").html("确认禁用该产品？");
    }else if(type==2){
        $("#me").html("确认解禁该产品？");

    }else if(type==3){
        $("#me").html("当前填写内容未提交，确认取消？");
    }else if(type==4){
        $("#me").html("该产品已存在");
    }else if(type==5){
        $("#me").html("确认删除此产品？");
    }else{

    }
    $('#modal-dialog').modal({backdrop: 'static', keyboard: false});
}

function doSomeThing() {
    var tid = $("#tid").val();
    var type = $("#typee").val();
    if (type==1){
        chageNotUse(tid);
    }else if(type==2){
        chageToUse(tid);
    }else if(type==3){
        window.location.href = "/product/toList";
    }else if(type==4){

    }else if(type==5){
        deleteById(tid);
    }else if(type==6){
        NoSure();
    }else if(type==7){
        Sure();
    }else{
        window.location.href="/product/toList";
    }
    $('#modal-dialog').modal('hide')
}

function openModel1(type) {
    var status = $("#myForm7").submit().parsley();
    if(status.isValid()){
        if(type==1){
            $("#typee").val(7);
            $("#me").html("确认审核通过？");
        }else if(type==2){
            $("#typee").val(6);
            $("#me").html("确认审核驳回？");
        }
        $('#modal-dialog').modal({backdrop: 'static', keyboard: false});
    }

}
//禁用
function chageNotUse(tid) {
    /*if(confirm("确认禁用该产品？")){
    }*/
        $.post(
            "/product/useStatus",
            {tid:tid,status:1},
            function (msg) {
                if (msg){
                    showAlread();
                    //location = location;
                }
            },"json"
        );

}
//启用
function chageToUse(tid) {
    /*if(confirm("确认解禁该产品？")){
    }*/
        $.post(
            "/product/useStatus",
            {tid:tid,status:0},
            function (msg) {
                if (msg){
                    showAlread();
                    //location = location;
                }
            },"json"
        );

}

function changeVal() {
    var value = $('#select :selected').val();
    var value3 = $('#select-required :selected').val();
    var flag = true;
    if(value!='请选择'&&value3!='请选择'&&value!=''&&value3!=''&&value!=null&&value3!=null){
        console.log("ccccccc"+value)
        $.ajax({
            url:'/product/checkProduct',
            type:'POST', //GET
            async:false,    //或false,是否异步
            data:{
                companyId:value,type:value3
            },
            dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
            success:function(data){
                if (data){
                    flag = false;
                    //alert("该产品已存在");
                    openModel(null,4);
                }
            }
        });
    }
    console.log(flag);
    return flag;
}

//取消
function cancle() {
    /*if(confirm("当前填写内容未提交，确认取消？")){
        //showRead();
    }*/
        window.location.href = "/product/toList";
}


//添加账期
function addTime() {
    var storage=window.localStorage;
    var i = storage.getItem("i");
    var sourceNode = document.getElementById("add");
    var clonedNode = sourceNode.cloneNode(true);
    clonedNode.setAttribute('id','add'+i);
    var sourceNode1 = document.getElementById("appendDiv");
    sourceNode1.parentNode.appendChild(clonedNode);
    $("#add"+i+" input:eq(0)").attr('name','collectionForm['+i+'].paymentDays');
    $("#add"+i+" input:eq(1)").attr('name','collectionForm['+i+'].earnings');
    $("#add"+i+" label:eq(0)").html('&nbsp;');
    $("#add"+i).removeClass('hidden');
    i = parseInt(i)+1;

    storage.setItem("i",i);
}

function Sure() {
    /*if(confirm("确认审核通过？")){
        return true;
    }
    return false;*/
    var role = $("#role").val();
    var url = null;
    var url2 = null;
    if(role == '0'){
        url =  "/product/checkProductByEmployee";
        url2 = "/product/toList";
    }else if(role == '1'){
        url =  "/product/checkProductByManager";
        url2 = "/product/toList?m=1";
    }
    $.ajax({
        url: url,
        type: "POST",
        data: $('#myForm7').serialize(),
        success: function (data) {
            if (data) {
                window.location.href = url2;

            }/* else {
                $("#me").html("新建失败！");
                openModel(null,8);
                return false;
            }*/
        }
    });
}
function NoSure() {
    /*if(confirm("确认审核驳回？")){
    }*/
    $.ajax({
        url: "/product/reject",
        type: "POST",
        data: $('#myForm7').serialize(),
        success: function (data) {
            if (data) {
                window.location.href = "/product/toList";

            }/* else {
             $("#me").html("新建失败！");
             openModel(null,8);
             return false;
             }*/
        }
    });
}

//只能为汉字或字符
window.ParsleyValidator.addValidator('dateTime', function(value) {
    if(value!= ""){
        return /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/.test(value);

    }
    return true;
},32);

window.ParsleyValidator.addValidator('numbers', function(value) {
    if(value!= ""){
        return /^[1-9]{1,3}$/.test(value);
    }
    return true;
},32);

window.ParsleyValidator.addValidator('unique', function(value) {
    var value = $('#select :selected').val();
    var value3 = $('#select-required :selected').val();
    var flag = true;
    if(value!='请选择'&&value3!='请选择'&&value!=''&&value3!=''&&value!=null&&value3!=null){
        console.log("ccccccc"+value)
        $.ajax({
            url:'/product/checkProduct',
            type:'POST', //GET
            async:false,    //或false,是否异步
            data:{
                companyId:value,type:value3
            },
            dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
            success:function(data){
                if (data){
                    flag = false;
                    //alert("该产品已存在");
                    //openModel(null,4);
                }
            }
        });
    }
    return flag;
},32);

function createProduct() {
    console.log(122212121212)
    //changeVal();
    var status = $('#myForm4').submit().parsley();
    if(status.isValid()){
        $.ajax({
            url: "/product/insert",
            type: "POST",
            data: $('#myForm4').serialize(),
            //必须false才会自动加上正确的Content-Type
            //必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
            success: function (data) {
                if (data) {
                    $("#me").html("新建成功！");
                    openModel(null,8);

                } else {
                    $("#me").html("新建失败！");
                    openModel(null,8);
                    return false;
                }
            }
        });
    }
}